﻿//***********************************************************************
// Assembly         : IGolovkine.AoA.Core
// Author           : Ilia
// Created          : 06-11-2011
//
// Last Modified By : Ilia
// Last Modified On : 01-10-2010
// Description      : 
//
// Copyright        : (c) Microsoft. All rights reserved.
//***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Globalization;

namespace IGolovkine.AoA.Tcp
{
    public class TcpConnection : IChannel<byte[]>
    {
        public const int DefaultBufferSize = 1024;
        private readonly AsyncStream _stream;
        private readonly Lazy<string> _desription;
        
        public TcpConnection(string host, int port) : this(new TcpClient(host, port))
        {
        }

        public TcpConnection(TcpClient client) 
        {
            _stream = new AsyncStream(client.GetStream(), DefaultBufferSize);
            _desription = new Lazy<string>(() => string.Format(CultureInfo.CurrentCulture, "Connection: {0} -> {1}", client.Client.LocalEndPoint, client.Client.RemoteEndPoint));
        }

        public IChannel<byte[]> Stream
        {
            get { return _stream; }
        }

        public IObservable<byte[]> Output
        {
            get { return _stream.Output; }
        }

        public IObserver<byte[]> Input
        {
            get { return _stream.Input; }
        }

        public override string ToString()
        {
            return _desription.Value;
        }
    }
}
